package com.liwy3.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Copyright © 元气森林（北京）食品科技集团有限公司. All rights reserved.
 *
 * @Description:
 * @author: Crazy4J
 * @date: 2021年12月07日 16:24
 * @version: V1.0
 */
@RestController
@Slf4j
public class JwtController {

    @GetMapping("/login")
    public void login() {
        System.out.println("hello jwt login");
        Map<String, Object> claims = new HashMap<>();
        //存放传递的参数
        claims.put("username", "liwy3");
        Date date = new Date(System.currentTimeMillis() + (50 * 1000));
        String token = Jwts.builder()
                .setClaims(claims)
                .setExpiration(date)
                .signWith(SignatureAlgorithm.HS512, "yK8vE5XgI79Thz4")
                .compact();
        System.out.println(token);
    }

    @GetMapping("/biz")
    public void biz(HttpServletRequest request) {
        String token = request.getHeader("token");
        System.out.println("hello biz ");
        Claims claims = getClaimsFromToken(token, "yK8vE5XgI79Thz4");
        final Date expiration = claims.getExpiration();
        Object username = claims.get("username");

        System.out.println("username:" + username);

    }

    private static Claims getClaimsFromToken(String token, String signing) throws RuntimeException {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(signing)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.error("签名异常：", e);
            throw new RuntimeException(e);
        }
        return claims;
    }
}
